﻿using System;
using System.Threading;

namespace PerfAssist.MemoryProfilerAdvanced.Editor.PAContrib
{
    public class StackInfoSynObj
    {
        public bool ReaderNewMsgArrived { get; private set; }

        public string StackInfo { get; private set; }

        public string readStackInfo()
        {
            if (StackInfo == null)
                return null;
            lock (this)
            {
                if (!ReaderNewMsgArrived)
                    try
                    {
                        Monitor.Wait(this);
                    }
                    catch (SynchronizationLockException e)
                    {
                        Console.WriteLine(e);
                    }
                    catch (ThreadInterruptedException e)
                    {
                        Console.WriteLine(e);
                    }

                ReaderNewMsgArrived = false;
                Monitor.Pulse(this);
            }

            return StackInfo;
        }

        public void writeStackInfo(string stackInfo)
        {
            lock (this)
            {
                if (ReaderNewMsgArrived)
                    try
                    {
                        Monitor.Wait(this);
                    }
                    catch (SynchronizationLockException e)
                    {
                        Console.WriteLine(e);
                    }
                    catch (ThreadInterruptedException e)
                    {
                        Console.WriteLine(e);
                    }

                StackInfo = stackInfo;
                ReaderNewMsgArrived = true;
                Monitor.Pulse(this);
            }
        }
    }
}